package com.pig.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;

public class FileUtil {

	private Properties pro;

	private String filePath;

	/**
	 * 构造方法，调用时初始化一个Properties对象
	 */
	public FileUtil() {
		pro = new Properties();
	}

	public Properties getProperty() {
		return pro;
	}

	/**
	 * 加载Properties文件
	 * 
	 * @param sFilePath
	 *            此Properties文件的路径
	 */
	public void loadProperty(String sFilePath) {
		String path = FileUtil.class.getClassLoader().getResource(sFilePath)
				.toString();
System.out.println("path:" + path);
		filePath = path.substring(path.indexOf("/") + 1);
System.out.println("filepath" + filePath);
		try {
			pro.load(new FileInputStream(filePath));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 保存Properties文件
	 */
	public void saveProperty() {
		try {
			pro.store(new FileOutputStream(filePath), null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setProperty(String key, String value) {
		pro.setProperty(key, value);
		this.saveProperty();
	}

	/**
	 * 由配置文件中的键获得其对应的值
	 * 
	 * @param key
	 *            键
	 * @return 键对应的值
	 */
	public String getPropertyValue(String key) {
		String value = pro.getProperty(key);
		return value;
	}

	public Map<Integer, String> getRevRanking(Properties pro) {
		Set set = pro.keySet();
		Object[] keys = set.toArray();
		TreeMap<Integer, String> ranking = new TreeMap<Integer, String>(
				Collections.reverseOrder());
		for (int i = 0; i < keys.length; i++) {
			ranking.put(Integer.valueOf(String.valueOf(keys[i])), String
					.valueOf(pro.get(keys[i])));
		}
		return ranking;
	}

	/**
	 * 由文件的相对路径获得绝对路径
	 * 
	 * @param path
	 *            文件的相对路径
	 * @returns 文件的绝对路径
	 */
	public String getFilePath(String path) {
System.out.println(path + "+path");
		String filePath = FileUtil.class.getClassLoader().getResource(path)
				.toString().substring(6);
System.out.println(filePath + "+filepath");
		return filePath;
	}
}
